package com.example.springbootrbac.handler;

import com.example.springbootrbac.pojo.Result;
import com.example.springbootrbac.pojo.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SecurityAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Autowired
    ObjectMapper objectMapper;
   //未登录拦截
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        String url = (httpServletRequest).getRequestURI();
        if (!"/register".equals(url)){
            httpServletResponse
                    .getWriter()
                    .write(objectMapper.writeValueAsString(Result.failure(ResultCode.FAILURE_FILTER_NOT_LOGIN_ERROR)));
        }else { //临时解决未登录时注册被拦截的情况
            httpServletRequest.getRequestDispatcher("/register").forward(httpServletRequest,httpServletResponse);
        }

    }
}
